package com.qj.platform.pay.controller;

import com.qj.base.commons.domain.SearchObject;
import com.qj.base.commons.utils.PropertiesUtil;
import com.qj.base.controller.BaseController;
import com.qj.base.domain.ResultTemplate;
import com.qj.platform.pay.core.service.MerchantService;
import com.qj.platform.pay.mssm.domain.Merchant;
import org.nutz.qrcode.QRCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;

/**
 * Created by zhijie on 2016/12/15.
 */
@RestController
@RequestMapping("/merchant")
public class MerchantController extends BaseController{
@Autowired
    private MerchantService merchantService;

    @RequestMapping("/_add")
    public ResultTemplate insert(Merchant merchant){
        merchantService.insert(merchant);
        return getSuccessTemplate();
    }

    @RequestMapping("/_update")
    public ResultTemplate update(Merchant merchant){
        merchantService.update(merchant);
        return getSuccessTemplate();
    }
    @RequestMapping("/_get")
    public ResultTemplate get(String id) throws IOException {
        Merchant merchant=merchantService.getById(id);
        merchant.setExtend1(PropertiesUtil.getProperty("mobile.baseUrl")+"/modules/mobile/index/index.html#/payPage/"+merchant.getMerchantId());
        BufferedImage image = QRCode.toQRCode(merchant.getExtend1());
        ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
        ImageIO.write(image,"jpg",outputStream);
        merchant.setExtend2("data:image/jpg;base64,"+Base64.getEncoder().encodeToString(outputStream.toByteArray()));
        return getSuccessTemplate(merchant);
    }

    @RequestMapping("/_query")
    public ResultTemplate query(SearchObject searchObject){
        return getSuccessTemplate(merchantService.query(searchObject),searchObject.getPageNum(),searchObject.getPageSize(),
                merchantService.queryCount(searchObject));
    }
}
